<template>
  <div>
    <!--搜索区域-->
    <div style="margin: 10px 5px">
      <el-input v-model="searchForm.productName" style="width: 20%" placeholder="商品名称" @input="debounceSearch"/>
      <el-select v-model="searchForm.categoryId" placeholder="商品分类" clearable style="width: 15%; margin-left: 10px" @change="search">
        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="商品状态" clearable style="width: 15%; margin-left: 10px" @change="search">
        <el-option :value="1" label="启用" />
        <el-option :value="0" label="停用" />
      </el-select>
      <el-button style="margin: 0 10px" type="primary" @click="search">查询</el-button>
      <el-button type="primary" @click="reset">重置</el-button>
    </div>
    <!--功能按钮区域-->
    <div style="margin: 10px 5px">
      <el-button type="primary" @click="add">新增商品</el-button>
      <el-button type="success" @click="importProducts">导入</el-button>
      <el-button type="warning" @click="exportProducts">导出</el-button>
    </div>
    <!--数据表格-->
    <el-table :data="tableData" ref="productTable" stripe style="width: 100%"
              @row-click="handleRowClick">
      <el-table-column type="selection" align="center"/>
      <el-table-column prop="productCode" label="商品编码" align="center"/>
      <el-table-column prop="productName" label="商品名称" width="200" align="center"/>
      <el-table-column prop="categoryName" label="商品分类" align="center"/>
      <el-table-column prop="specification" label="规格" width="200" align="center"/>
      <el-table-column prop="unit" label="单位" align="center"/>
      <el-table-column prop="purchasePrice" label="采购价" align="center"/>
      <el-table-column prop="sellingPrice" label="销售价" align="center"/>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
          <el-tag v-else type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="minStock" label="最小库存" align="center"/>
      <el-table-column prop="maxStock" label="最大库存" align="center"/>
      <el-table-column prop="createTime" label="创建时间" width="200" align="center">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="200">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
          <el-popconfirm title="确定删除该商品吗？" @confirm="handleDelete(scope.row.productId)">
            <template #reference>
              <el-button link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div style="margin: 10px 0">
      <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!--商品表单对话框-->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增商品' : dialogType === 'edit' ? '编辑商品' : '查看商品'" width="60%" @close="dialogClose">
      <el-form v-if="form" :model="form" :rules="rules" ref="productForm" label-width="120px" :disabled="dialogType === 'view'">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="productCode">
              <template #label>
                <span>
                  <el-tooltip content="商品的唯一标识符，类似商品的'身份证号'，用于在系统中快速查找和追踪商品" placement="top">
                    商品编码
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.productCode" placeholder="请输入商品编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="productName">
              <template #label>
                <span>
                  <el-tooltip content="商品的具体名称，直观描述商品，便于理解和识别" placement="top">
                    商品名称
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.productName" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="categoryId">
              <template #label>
                <span>
                  <el-tooltip content="商品所属的类别，帮助组织和管理不同类型的商品，便于分类查询和报表统计" placement="top">
                    商品分类
                  </el-tooltip>
                </span>
              </template>
              <el-select v-model="form.categoryId" placeholder="请选择商品分类" style="width: 100%">
                <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="specification">
              <template #label>
                <span>
                  <el-tooltip content="商品的具体型号、尺寸或特性，详细描述商品的具体特征，帮助区分同类但不同规格的商品" placement="top">
                    规格
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.specification" placeholder="请输入规格"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="unit">
              <template #label>
                <span>
                  <el-tooltip content="商品的计量单位，如'个'、'台'、'箱'、'公斤'等，明确商品如何计数，对库存管理和销售统计非常重要" placement="top">
                    单位
                  </el-tooltip>
                </span>
              </template>
              <el-input v-model="form.unit" placeholder="请输入单位"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status">
              <template #label>
                <span>
                  <el-tooltip content="商品是否可用，启用表示商品可正常销售和采购，停用表示商品暂时不可用" placement="top">
                    状态
                  </el-tooltip>
                </span>
              </template>
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="purchasePrice">
              <template #label>
                <span>
                  <el-tooltip content="企业从供应商处购买该商品的成本价格，用于成本核算和利润分析" placement="top">
                    采购价
                  </el-tooltip>
                </span>
              </template>
              <el-input-number v-model="form.purchasePrice" :precision="2" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="sellingPrice">
              <template #label>
                <span>
                  <el-tooltip content="企业向客户销售该商品的价格，用于销售收入计算和价格管理" placement="top">
                    销售价
                  </el-tooltip>
                </span>
              </template>
              <el-input-number v-model="form.sellingPrice" :precision="2" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="minStock">
              <template #label>
                <span>
                  <el-tooltip content="库存警戒线，低于此数量系统会提醒补货，避免缺货导致销售损失" placement="top">
                    最小库存
                  </el-tooltip>
                </span>
              </template>
              <el-input-number v-model="form.minStock" :min="0" :precision="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="maxStock">
              <template #label>
                <span>
                  <el-tooltip content="库存上限，超过此数量可能造成资金占用和仓储压力，控制过量采购，优化库存结构" placement="top">
                    最大库存
                  </el-tooltip>
                </span>
              </template>
              <el-input-number v-model="form.maxStock" :min="0" :precision="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item prop="remark">
          <template #label>
            <span>
              <el-tooltip content="关于商品的额外信息，可记录特殊要求、存储条件、供应商信息等" placement="top">
                备注
              </el-tooltip>
            </span>
          </template>
          <el-input v-model="form.remark" type="textarea" rows="3" placeholder="请输入备注信息"/>
        </el-form-item>
      </el-form>
      <div v-else class="loading-container">
        <el-empty v-if="dialogType !== 'add'" description="正在加载数据..."></el-empty>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="saveProduct">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!--导入对话框-->
    <el-dialog v-model="importDialogVisible" title="导入商品" width="30%">
      <el-upload
        class="upload-demo"
        drag
        action="/api/product/import"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        accept=".xls,.xlsx"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传Excel文件，且文件大小不超过500kb
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { UploadFilled } from '@element-plus/icons-vue'
import {
  listProduct,
  getProduct,
  addProduct,
  updateProduct,
  delProduct,
  exportProduct,
  listAllCategory
} from '@/api/product'

export default {
  name: 'ProductView',
  components: {
    UploadFilled
  },
  data() {
    return {
      // 表格数据
      tableData: [],
      total: 0,
      // 搜索条件
      searchForm: {},
      // 分类选项
      categoryOptions: [],
      // 对话框控制
      dialogVisible: false,
      dialogType: 'add', // add, edit, view
      importDialogVisible: false,
      searchTimer: null,//搜索定时器
      // 表单数据
      form: {
        purchasePrice: 0,
        sellingPrice: 0,
        status: 1,
        minStock: 0,
        maxStock: 9999,
      },
      // 表单验证规则
      rules: {
        productCode: [
          { required: true, message: '请输入商品编码', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ],
        purchasePrice: [
          { required: true, message: '请输入采购价', trigger: 'blur' }
        ],
        sellingPrice: [
          { required: true, message: '请输入销售价', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchCategoryOptions();
    this.getList();

    // 添加ResizeObserver错误捕获
    window.addEventListener('error', (e) => {
      if (e && e.message && (
          e.message === 'ResizeObserver loop limit exceeded' ||
          e.message.includes('ResizeObserver loop completed with undelivered notifications')
      )) {
        const resizeObserverErr = e;
        resizeObserverErr.stopImmediatePropagation();
      }
    }, true);
  },
  methods: {
    // 防抖搜索函数
    debounceSearch() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }

      //setTimeout函数 延迟触发或者是延迟加载
      //searchTimer是定时器, 是setTimeout函数的返回值, 其中记录着定时任务
      //如果用户在250毫秒期间继续输入, 那么会清除旧的定时器, 即清除尚未执行的搜索
      this.searchTimer = setTimeout(() => {
        this.search();
      }, 250);
    },

    // 获取商品分类选项
    fetchCategoryOptions() {
      listAllCategory().then(res => {
        if (res.code === 200) {
          this.categoryOptions = res.data.map(item => {
            return {
              value: item.categoryId,
              label: item.categoryName
            }
          });
        } else {
          this.$message.error('获取商品分类失败');
        }
      });
    },

    // 获取商品列表
    getList() {
      listProduct(this.searchForm).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        } else {
          this.$message.error('获取商品列表失败');
        }
      });
    },

    // 搜索
    search() {
      this.searchForm.pageNum = 1;
      this.getList();
    },

    // 重置
    reset() {
      this.searchForm = {};
      this.searchForm.pageNum = 1;
      this.getList();
    },

    // 新增商品
    add() {
      this.dialogType = 'add';
      this.dialogVisible = true;
      this.form = {
        purchasePrice: 0,
        sellingPrice: 0,
        status: 1,
        minStock: 0,
        maxStock: 9999,
      };
      // 清空表单验证
      if (this.$refs.productForm) {
        this.$refs.productForm.resetFields();
      }
    },

    // 编辑商品
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogVisible = true;
      getProduct(row.productId).then(res => {
        if (res.code === 200) {
          this.form = res.data;
        } else {
          this.$message.error('获取商品信息失败');
        }
      });
    },

    // 查看商品
    handleView(row) {
      this.dialogType = 'view';
      this.dialogVisible = true;
      getProduct(row.productId).then(res => {
        if (res.code === 200) {
          this.form = res.data;
        } else {
          this.$message.error('获取商品信息失败');
        }
      });
    },

    // 删除商品
    handleDelete(id) {
      delProduct(id).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.getList();
        } else {
          this.$message.error('删除失败');
        }
      });
    },

    // 保存商品
    saveProduct() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          if (this.dialogType === 'add') {
            // 新增
            addProduct(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success('添加成功');
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg || '添加失败');
              }
            });
          } else {
            // 编辑
            updateProduct(this.form).then(res => {
              if (res.code === 200) {
                this.$message.success('修改成功');
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg || '修改失败');
              }
            });
          }
        }
      });
    },

    // 导入商品
    importProducts() {
      this.importDialogVisible = true;
    },

    // 导入成功回调
    handleImportSuccess(response) {
      if (response.code === 200) {
        this.$message.success(`成功导入${response.successCount}条记录`);
        this.importDialogVisible = false;
        this.getList();
      } else {
        this.$message.error(response.msg || '导入失败');
      }
    },

    // 导入失败回调
    handleImportError() {
      this.$message.error('文件上传失败');
    },

    // 导出商品
    exportProducts() {
      const query = {
        productName: this.searchForm.productName || '',
        categoryId: this.searchForm.categoryId || '',
        status: this.searchForm.status !== '' ? this.searchForm.status : ''
      }

      exportProduct(query).then(res => {
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = '商品数据.xlsx';
        link.click();
      });
    },

    // 分页切换
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.getList();
    },

    // 处理行点击
    handleRowClick(row) {
      this.$refs.productTable.toggleRowSelection(row);
    },

    // 对话框关闭时重置表单
    dialogClose() {
      if (this.$refs.productForm) {
        this.$refs.productForm.resetFields();
      }
    },
  }
}
</script>

<style scoped>
.dialog-footer {
  padding: 10px 0;
  text-align: right;
}
</style>
